package com.lgkj.ui.main;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleIndicateCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.lgkj.R;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/8/20 0020.
 */

public class MeiDianFragment extends Fragment implements SeekBar.OnSeekBarChangeListener {
    private static final String TAG = "MeiDianFragment";
    @BindView(R.id.seekbar)
    SeekBar seekbar;
    @BindView(R.id.ibtn_start)
    ImageButton iBtnStart;
    @BindView(R.id.tv_play)
    TextView tvPlay;
    @BindView(R.id.tv_fudu)
    TextView tvFudu;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_suspend)
    TextView tvSuspend;
    @BindView(R.id.tv_shuifen)
    TextView tvShuifen;
    @BindView(R.id.tv_youxing)
    TextView tvYouxing;
    private View view;
    private BleDevice mDevice;
    private List<BluetoothGattService> servicesList;
    private BluetoothGattCharacteristic characteristic, readcharacteristic;
    //获取系统蓝牙适配器管理类
    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
            .getDefaultAdapter();

    private MediaPlayer mMediaPlayer;
    private int[] musics = {R.raw.one, R.raw.two, R.raw.three};
    private boolean isSucess = false;
    private String[] sendText = {"0x01", "0x08", "0x10", "0x20", "0x30", "0x40", "0x48", "0x50",
            "0x58", "0x60", "0x70", "0x80", "0x90", "0xa0", "0xb0", "0xf0"};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_meidian_fragment, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        test1();
        seekbar.setOnSeekBarChangeListener(this);
        if (!isSucess)
            init();
    }

    private void init() {
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {

            }

            @Override
            public void onScanStarted(boolean success) {

            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                if (bleDevice.getName() != null) {
                    Log.i(TAG, "onScanning: " + (bleDevice.getName().indexOf("DMK28") != -1));
                    if (bleDevice.getName().indexOf("DMK28") != -1) {
                        mDevice = bleDevice;
                        Log.i(TAG, "onScanning: is  stop");
                        BleManager.getInstance().cancelScan();
                        connect(bleDevice);
                    }
                }
            }
        });
    }

    private void connect(final BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.i(TAG, "onConnectFail: " + exception.getDescription());
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                Log.i(TAG, "onConnectSuccess: " + gatt.getServices().size());
                servicesList = gatt.getServices();
                iBtnStart.setBackgroundResource(R.mipmap.boolue_statue_0);
                if (servicesList.size() > 0) {
                    BluetoothGattService readService = servicesList.get(0);
                    readcharacteristic = readService.getCharacteristics().get(0);
                    BluetoothGattService writeService = servicesList.get(1);
                    characteristic = writeService.getCharacteristics().get(0);
                    Log.i(TAG, "if: " + readcharacteristic.getUuid().toString());
                    Log.i(TAG, "if: " + characteristic.getUuid().toString());
                }
                playMusic(0);
                send("01fe000023331000ff00000000000000");  //打开净化
                send("01fe000023351000ff00000000000000");   //幅度(导入)打开
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {

            }
        });
    }

    private void playMusic(int i) {
        try {
            Log.i(TAG, "playMusic: " + i);
            if (i > 2 || i < 0) {
                i = 0;
            }
            mMediaPlayer = MediaPlayer.create(getActivity(), musics[i]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mMediaPlayer.start();
        playFinish();
    }

    /**
     * 净化打开
     * 01fe8600410098000211412901030000001f0000
     * 01fe000023331000ff00000000000000
     *
     * @param str
     */


    private void send(String str) {
        if (characteristic == null) {
            return;
        }
        BleManager.getInstance().write(
                mDevice,
                characteristic.getService().getUuid().toString(),
                characteristic.getUuid().toString(),
                HexUtil.hexStringToBytes(str), new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        Log.e(TAG, "写入: " + HexUtil.formatHexString(justWrite));
                    }

                    @Override
                    public void onWriteFailure(BleException exception) {
                        Log.i(TAG, "onWriteFailure: " + exception.getDescription());
                    }
                });
        indeicate();
    }

    /**
     * 接受通知
     */
    private boolean isIndeicate = false;

    private void indeicate() {
        if (isIndeicate) return;
        isIndeicate = true;
        BleManager.getInstance().indicate(mDevice, readcharacteristic.getService().getUuid().toString(),
                readcharacteristic.getUuid().toString(), new BleIndicateCallback() {
                    @Override
                    public void onIndicateSuccess() {
                        Log.i(TAG, "onIndicateSuccess: ");
                    }

                    @Override
                    public void onIndicateFailure(BleException exception) {
                        Log.i(TAG, "onIndicateFailure: " + exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        Log.e(TAG, "读取: " + HexUtil.formatHexString(data));
                        initData(HexUtil.formatHexString(data));
                    }
                });
    }

    /**
     * 01fe8600410098 000535 412a01020000001f0000
     *
     * @param result
     */
    private void initData(String result) {
        if (result.length() == 40) {
            String times = result.substring(14, 20);
            Log.i(TAG, "initData: " + times);
            String time = times.substring(0, 2) + "时" + Integer.valueOf(times.substring(2, 4), 16) + "分" + Integer.valueOf(times.substring(4, times.length()), 16) + "秒";
            Log.i(TAG, "initData: " + time);


            String shuifen = Integer.valueOf(result.substring(20, 22), 16) + "";
            Log.i(TAG, "initData: " + shuifen);
            tvTime.setText(time);
            tvShuifen.setText("水分: " + shuifen);
            String youfen = Integer.valueOf(result.substring(22, 24), 16) + "";
            tvYouxing.setText("油性: " + youfen);
        }
    }

    private int count = 0;

    @OnClick({R.id.ibtn_jian, R.id.ibtn_start, R.id.ibtn_add, R.id.tv_suspend, R.id.tv_play})
    public void onClick(View view) {
        try {
            count = Integer.parseInt(tvFudu.getText().toString());
        } catch (NumberFormatException e) {
            count = 0;
            Log.e(TAG, "onClick: " + e.getMessage());
        }
        switch (view.getId()) {
            case R.id.ibtn_jian:
                if (count > 1) {
                    count--;
                    send("01fe000023371000" + sendText[count - 1] + "00000000000000");
                    tvFudu.setText(count + "");
                    seekbar.setProgress(count);
                }
                break;
            case R.id.ibtn_start:
                if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(
                            BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, 1);
                }
                if (!isSucess) {
                    init();
                }

                break;
            case R.id.ibtn_add:
                if (count < 15) {
                    count = count + 1;
                    send("01fe000023371000" + sendText[count] + "00000000000000");
                    seekbar.setProgress(count);
                    tvFudu.setText(count + "");
                }
                break;
            case R.id.tv_suspend:
                if (mMediaPlayer != null)
                    mMediaPlayer.pause();
                break;
            case R.id.tv_play:
                if (mMediaPlayer != null)
                    mMediaPlayer.start();
                break;
        }

        Log.i(TAG, "onClick: " + count);


    }

    private int position = 0;

    private void playFinish() {
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                position++;
                playMusic(position);
            }
        });
    }

    @Override
    public void onDestroy() {
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();//停止音频的播放
        }
        mMediaPlayer.release();//释放资源
        super.onDestroy();
    }


    public void test1() {
        // 单位: 毫秒
        final long timeInterval = 20000;
        Runnable runnable = new Runnable() {
            public void run() {
                while (true) {
                    try {
                        if (mDevice != null) {
                            isSucess = BleManager.getInstance().isConnected(mDevice);
                        }
                        Thread.sleep(timeInterval);
                        mHandler.sendEmptyMessage(0);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }


    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (!isSucess) {
                        iBtnStart.setBackgroundResource(R.mipmap.boolue_statue);
                    } else {
                        iBtnStart.setBackgroundResource(R.mipmap.boolue_statue_0);
                    }
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        Log.i(TAG, "onProgressChanged: ");

        tvFudu.setText(progress + "");
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        Log.i(TAG, "onStartTrackingTouch: ");
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int progress = seekBar.getProgress();
        Log.i(TAG, "onStopTrackingTouch: "+progress);
        send("01fe000023371000" + sendText[progress-1] + "00000000000000");
    }
}
